/**
 * axios 二次封装
 */

import axios from "axios";
// import config from "@/config";
import { ElMessage } from "element-plus";
import router from "@/router";
const BASE_URL = "https://jdfi"
const TOKEN_INVALID = "Token认证失败，请重新登陆";
const NETWORK_ERROR = "网络请求异常，请稍后重试";

// 创建axios实例对象，添加全局配置
const service = axios.create({
  baseURL: BASE_URL,
  timeout: 10000,
});

// 请求拦截
service.interceptors.request.use((req) => {
  const headers = req.headers;
  if (!headers.Authorization) headers.Authorization = "Bear QiTest";
  return req;
});

// 响应拦截
service.interceptors.response.use((res) => {
  const { code, data, msg } = res.data;
  if (code === 200) {
    return data;
  } else if (code === 40001) {
    ElMessage.error(TOKEN_INVALID);
    setTimeout(() => {
      router.push("/login");
    }, 15000);
    return Promise.reject(TOKEN_INVALID);
  } else {
    ElMessage.error(NETWORK_ERROR);
    return Promise.reject(NETWORK_ERROR);
  }
});

/**
 * 请求核心函数
 * @param {*} options 请求配置
 */
const request = (options) => {
  return new Promise((resolve, reject) => {
    options.method = options.method || "get";
    if (options.method.toLowerCase() === "get") {
      options.params = options.data;
    }
    if (BASE_URL) {
      service.defaults.baseURL = BASE_URL;
    } 
    if (options.mock) {
      service.defaults.baseURL = config.mockApi;
    }
    service(options)
      .then((res) => resolve(res))
      .catch((error) => reject(error));
  });
};

export default request;
